package com.changan.remote.assistant;

import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

/**
 * <pre>
 *     @author : xujl
 *     e-mail : 597355068@qq.com
 *     time   : 2018/11/8
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class RemoteAssistantManager {
    private static final String ACTION = "com.xujl.datalibrary.RemoteServer";
    private static final String ASSISTANT_PACKAGE_NAME = "com.xujl.demo";
    private Application mApplication;
    private IRemoteAssisant mRemoteAssisant;
    private IAssisantCallback.Stub mCallback;

    private RemoteAssistantManager () {

    }

    public void init (Application application) {
        mApplication = application;
        bindService();
    }

    public void sendEvent (String json) {
        try {
            if (mRemoteAssisant != null) {
                mRemoteAssisant.sendEvent(json);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void recycle () {
        unbindService();
    }

    public void registerListener (IAssisantCallback.Stub callback) {
        mCallback = callback;
    }

    public void unregisterListener (IAssisantCallback.Stub callback) {
        if (mRemoteAssisant != null) {
            try {
                mRemoteAssisant.unRegisterListener(callback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        mCallback = null;
    }

    private void bindService () {
        Intent intent = new Intent();
        intent.setAction(ACTION);
        intent.setPackage(ASSISTANT_PACKAGE_NAME);
        mApplication.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    private void unbindService () {
        mApplication.unbindService(mConnection);
    }

    private void registerListener () {
        if (mCallback == null || mRemoteAssisant == null) {
            return;
        }
        try {
            mRemoteAssisant.registerListener(mCallback);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected (final ComponentName name, final IBinder service) {
            mRemoteAssisant = IRemoteAssisant.Stub.asInterface(service);
            registerListener();
        }

        @Override
        public void onServiceDisconnected (final ComponentName name) {
            mRemoteAssisant = null;
        }
    };

    public static RemoteAssistantManager getInstance () {
        return Holder.MANAGER;
    }

    private static class Holder {
        private static final RemoteAssistantManager MANAGER = new RemoteAssistantManager();
    }
}